#include <iostream>  
using namespace std;  
  
// 定义二叉树节点结构体  
struct TreeNode {  
    int val;  
    TreeNode* left;  
    TreeNode* right;  
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
};  
  
// 插入节点  
void insert(TreeNode*& root, int val) {  
    if (root == NULL) {  
        root = new TreeNode(val);  
        return;  
    }  
    if (val < root->val) {  
        insert(root->left, val);  
    } else {  
        insert(root->right, val);  
    }  
}  
  
// 查找最小节点  
TreeNode* findMin(TreeNode* root) {  
    while (root->left != NULL) {  
        root = root->left;  
    }  
    return root;  
}  
  
// 删除节点  
void deleteNode(TreeNode*& root, int val) {  
    if (root == NULL) {  
        return;  
    }  
    if (val < root->val) {  
        deleteNode(root->left, val);  
    } else if (val > root->val) {  
        deleteNode(root->right, val);  
    } else {  
        if (root->left == NULL) {  
            TreeNode* temp = root->right;  
            delete root;  
            root = temp;  
        } else if (root->right == NULL) {  
            TreeNode* temp = root->left;  
            delete root;  
            root = temp;  
        } else {  
            TreeNode* minNode = findMin(root->right);  
            root->val = minNode->val;  
            deleteNode(root->right, minNode->val);  
        }  
    }  
}  
  
// 中序遍历二叉树（递归实现）  
void inorderTraversal(TreeNode* root) {  
    if (root == NULL) {  
        return;  
    }  
    inorderTraversal(root->left);  
    cout << root->val << " ";  
    inorderTraversal(root->right);  
}  
  
// 中序遍历二叉树（迭代实现）  
void inorderTraversalIterative(TreeNode* root) {  
    if (root == NULL) {  
        return;  
    }  
    stack<TreeNode*> nodeStack;  
    TreeNode* current = root;  
    while (current != NULL || !nodeStack.empty()) {  
        while (current != NULL) {  
            nodeStack.push(current);  
            current = current->left;  
        }  
        current = nodeStack.top();  
        nodeStack.pop();  
        cout << current->val << " ";  
        current = current->right;  
    }  
}